package com.example.carborrow.service;

import com.example.carborrow.dao.CustomerDao;
import com.example.carborrow.model.Customer;
import com.example.carborrow.model.Vip;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CustomerService {
    private final CustomerDao cusDao;
    private final VipService vipService;

    @Autowired
    public CustomerService(CustomerDao cusDao, VipService vipService) {
        this.cusDao = cusDao;
        this.vipService = vipService;
    }

    public List<Customer> getAllCus() {
        return cusDao.getAllCus();
    }

    public List<Customer> getCusByName(String name) {
        return cusDao.getCusByName(name);
    }

    public Customer getCusByPhone(String phone) {
        return cusDao.getCusByPhone(phone);
    }

    public Customer getCusById(int id) {
        return cusDao.getCusById(id);
    }


    public boolean addCustomer(String name , String phone , String password) {
        return cusDao.addCustomer( name,phone,password) >0;
    }


    public boolean updateCustomer(Customer cus) {
        return cusDao.updateCustomer(cus) >0;
    }



    @Transactional
    public boolean addCustomerPaysBalance(int customerId , BigDecimal add) {
        Customer cus = getCusById(customerId);
        if (cus == null) return false;
        BigDecimal afterPays =  cus.getPays().add(add);
        BigDecimal afterBalance = cus.getBalance().add(add);
        int checkLevel =  CheckCusVip(cus,afterPays);
        if(cus.getVipLevel() != checkLevel){
            return cusDao.updateCustomerPaysBalanceLevel(customerId,afterPays,afterBalance,checkLevel)>0;
        }
        else return cusDao.updateCustomerPaysBalance(customerId,afterPays,afterBalance)>0;

    }

    private int CheckCusVip(Customer cus,BigDecimal afterPays){
        List<Vip> vipList = vipService.getAllVip();
        int  Maxlevel = 0;
        for (Vip vip:vipList) {
            if(afterPays.compareTo(vip.getVipPrice())>=0){
                Maxlevel = vip.getLevel();

            }
        }
        return Maxlevel;
    }
    public boolean subCustomerPaysBalance(int customerId,BigDecimal subAmount){
        Customer cus = getCusById(customerId);
        if (cus == null) return false;
        BigDecimal afterBalance = cus.getBalance().subtract(subAmount);
        if (afterBalance.compareTo(BigDecimal.ZERO)<0) return false;
        return cusDao.updateCustomerBalance(customerId,afterBalance)>0;

    }



    public boolean deleteCustomer(int customerId) {
        return cusDao.deleteCustomer(customerId) >0;

    }





}

